package javapop.framework.parser;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class Regexp extends Parser<MatchResult> {
	private Pattern regexp;
	private String description;
	
	public Regexp(String regexp) {
		if(regexp==null)
			throw new IllegalArgumentException("Regexp is null");
		this.regexp = Pattern.compile(regexp);
		description = regexp;
	}
	
	@Override
	public String getDescription() {
		return description;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public final ParseResult<MatchResult> eval(ParseContext ctx, ParseInput input) {
		String line = input.thisLine();
		Matcher matcher = regexp.matcher(line);
		if(!matcher.lookingAt()) {
			return (ParseResult) new ParseError("Expecting regexp: "+description);
		}
		input.move(input.getPos()+matcher.end());
		ParseResult<MatchResult> result = buildResult(matcher);
		return result;
	}
	
	@Override
	public boolean isMemoized() {
		return true;
	}
	
	@Override
	public int hashCode() {
		return description.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null) return false;
		if(obj==this) return true;
		if(obj.getClass()!=this.getClass())
			return false;
		return ((Regexp) obj).regexp.equals(regexp);
	}
	
}
